let toggle_kind = '1';

function addListenerForToogle() {
    let toggle_open = document.querySelector('.toggle-open');
    toggle_open.addEventListener('click', function () {
        let de = document.querySelector('.list-info-description');
        let more_de = document.querySelector('.list-info-more-description');
        if (toggle_kind === '1') {
            toggle_open.innerHTML = '收起<i class="bi bi-chevron-up"></i>';
            de.setAttribute('style', 'display:none');
            more_de.setAttribute('style', 'display:block');
            post_Message();
            toggle_kind = '0';
        } else {
            toggle_open.innerHtml = '展开<i class="bi bi-chevron-down"></i>';
            more_de.setAttribute('style', 'display:none');
            de.setAttribute('style', 'display:block');
            post_Message();
            toggle_kind = '1';
        }
    });
}

if (getQueryString('type') === 'playlist') {
    let type_info = document.querySelector('.type-info');
    type_info.innerHTML = '<div class="list-info-name"></div>\n' +
        '                                        <div class="list-info-updateTime"></div>\n' +
        '                                        <div class="list-info-creator"></div>\n' +
        '                                        <div class="list-info-cat"></div>\n' +
        '                                        <div>\n' +
        '                                            <span class="list-info-playCount"></span>\n' +
        '                                            <span class="list-info-subscribedCount ms-2"></span>\n' +
        '                                            <span class="list-info-commentCount ms-2"></span>\n' +
        '                                        </div>\n' +
        '                                        <div class="list-info-description">\n' +
        '                                        </div>\n' +
        '                                        <div class="list-info-more-description">\n' +
        '                                        </div>'
    getPlaylist();
} else if (getQueryString('type') === 'album') {
    let type_info = document.querySelector('.type-info');
    type_info.innerHTML = '<div class="list-info-name"></div>\n' +
        '<div class="list-info-creator"></div>\n<div class="publishTime"></div>\n<div class="company"></div>\n' +
        '<div>\n' +
        '                                            <span class="list-info-subscribedCount"></span>\n' +
        '                                            <span class="list-info-commentCount ms-2"></span>\n' +
        '                                        </div>\n' +
        '      <div class="list-info-description">\n' +
        '                                        </div>\n' +
        '                                        <div class="list-info-more-description">\n' +
        '                                        </div>'
    getAlbum();
} else {
    let type_info = document.querySelector('.type-info');
    type_info.innerHTML = '<div class="list-info-name"></div>\n' +
        '<div class="list-info-creator my-1"></div>\n<div class="from-album my-1"></div>\n' +
        '<div class="song-time-length my-1"></div>\n               <div class="songs-buttonGroup my-1">\n' +
        '                                            <button class="btn btn-primary rounded-pill btn-sm"><i\n' +
        '                                                class="bi bi-play "></i>播放\n' +
        '                                        </button>\n' +
        '                                            <button class="btn btn-primary mx-2 rounded-pill btn-sm"><i\n' +
        '                                                    class="bi bi-plus-lg "></i>收藏\n' +
        '                                            </button>\n' +
        '                                        </div>\n' +
        '<div class="song-lyric ms-3 my-1"></div>';
    let songs_none = document.querySelectorAll('.songs-none');
    for (let i = songs_none.length - 1; i >= 0; i--) {
        songs_none[i].parentNode.removeChild(songs_none[i]);
    }
    getSingleSong();
}

function getPlaylist() {
    axios.all([getListInfo(), getAllSongs(), getRelated()])
        .then(axios.spread(function (res1, res2, res3) {
            buildList_info(res1);
            buildAllSongsTables(res2);
            relatedPlaylists(res3);
            addListenerForToogle();
            post_Message();
        })).catch(error => {
        console.log(error);
    });
}

function getSingleSong() {
    axios.all([getSingleSongInfo(), getSingleSongsLrc(), getSimiSong()])
        .then(axios.spread(function (res1, res2, res3) {
            buildSingleSong_info(res1, res2);
            buildSimiSong(res3);
            post_Message();
        })).catch(error => {
        console.log(error);
    });
}

function getAlbum() {
    axios.all([getAlumInfoOfSong(), getOtherAlbums()])
        .then(axios.spread(function (res1, res2) {
            buildAlbum_info(res1);
            buildOtherSongs(res2);
            addListenerForToogle();
            post_Message();
        })).catch(error => {
        console.log(error);
    });
}

function getSimiSong() {
    return axios.get(`http://localhost:3000/simi/song?id=${getQueryString('songId')}`);
}

function getSingleSongInfo() {
    return axios.get(`http://localhost:3000/song/detail?ids=${getQueryString('songId')}`);
}

function getSingleSongsLrc() {
    return axios.get(`http://localhost:3000/lyric?id=${getQueryString('songId')}`);
}

function getOtherAlbums() {
    return axios.get(`http://localhost:3000/artist/album?id=${getQueryString('singerId')}&limit=5`);
}

function getAlumInfoOfSong() {
    return axios.get(`http://localhost:3000/album?id=${getQueryString('albumId')}`);
}

function getListInfo() {
    return axios.get(`http://localhost:3000/playlist/detail?id=${getQueryString('listId')}`);
}

function getAllSongs() {
    return axios.get(`http://localhost:3000/playlist/track/all?id=${getQueryString('listId')}&limit=${getQueryString('trackCount')}&offset=0`);
}

function getRelated() {
    return axios.get(`http://localhost:3000/related/playlist?id=${getQueryString('listId')}`);
}

function buildSingleSong_info(res, res1) {
    let coverImg = document.querySelector('.playlist-coverImg');
    let name = document.querySelector('.list-info-name');
    let creator = document.querySelector('.list-info-creator');
    let from_album = document.querySelector('.from-album');
    let dt = document.querySelector('.song-time-length');
    let lyc = document.querySelector('.song-lyric');
    coverImg.src = res.data['songs'][0]['al']['picUrl'];
    name.innerHTML = ' <span class="badge rounded-pill bg-info">单曲</span>&nbsp;' + res.data['songs'][0]['name'];
    creator.innerHTML = '歌手：' + getAlbumCreator(res.data['songs'][0]['ar']);
    from_album.innerHTML = '所属专辑：<span>' + res.data['songs'][0]['al']['name'] + '</span>';
    dt.innerHTML = '时长：' + changeDt(res.data['songs'][0]['dt']);
    lyc.innerText = getlyric(res1.data['lrc']['lyric']);
}

function buildAlbum_info(res) {
    let coverImg = document.querySelector('.playlist-coverImg');
    let name = document.querySelector('.list-info-name');
    let subscribedCount = document.querySelector('.list-info-subscribedCount');
    let commentCount = document.querySelector('.list-info-commentCount');
    let description = document.querySelector('.list-info-description');
    let more_description = document.querySelector('.list-info-more-description');
    let creator = document.querySelector('.list-info-creator');
    let publishTime = document.querySelector('.publishTime');
    let company = document.querySelector('.company');
    coverImg.src = res.data['album']['blurPicUrl'];
    name.innerHTML = ' <span class="badge rounded-pill bg-info">专辑</span>&nbsp;' + res.data['album']['name'];
    creator.innerHTML = '歌手：' + getAlbumCreator(res.data['album']['artists']);
    subscribedCount.innerHTML = '<i class="bi bi-heart"></i>&nbsp;' + changePlayCount(res.data['album']['info']['likedCount']);
    commentCount.innerHTML = '<i class="bi bi-chat-dots"></i>&nbsp;' + changePlayCount(res.data['album']['info']['commentCount']);
    description.innerText = limitDescriptionLength('专辑介绍：' + res.data['album']['description']);
    more_description.innerText = '专辑介绍：' + res.data['album']['description'];
    company.innerText = '发行公司：' + res.data['album']['company'];
    publishTime.innerText = '发行时间：' + formatDate1(res.data['album']['publishTime']);
    let trackCount = document.querySelector('.table-list-trackCount');
    trackCount.innerText = res.data['songs'].length + '首歌';
    buildAllSongsTables(res);
}

function buildList_info(res) {
    let coverImg = document.querySelector('.playlist-coverImg');
    let name = document.querySelector('.list-info-name');
    let cat = document.querySelector('.list-info-cat');
    let playCount = document.querySelector('.list-info-playCount');
    let subscribedCount = document.querySelector('.list-info-subscribedCount');
    let commentCount = document.querySelector('.list-info-commentCount');
    let description = document.querySelector('.list-info-description');
    let more_description = document.querySelector('.list-info-more-description');
    let trackCount = document.querySelector('.table-list-trackCount');
    let updateTime = document.querySelector('.list-info-updateTime');
    let creator = document.querySelector('.list-info-creator');
    coverImg.src = res.data['playlist']['coverImgUrl'];
    name.innerHTML = ' <span class="badge rounded-pill bg-info">歌单</span>&nbsp;' + res.data['playlist']['name'];
    updateTime.innerText = formatDate(res.data['playlist']['updateTime']) + ' 更新';
    creator.innerHTML = 'by&nbsp;<span>' + res.data['playlist']['creator']['nickname'] + '</span>'
    cat.innerText = getStringsTags(res.data['playlist']['tags']);
    playCount.innerHTML = '<i class="bi bi-headphones"></i>&nbsp;' + changePlayCount(res.data['playlist']['playCount']) + '次'
    subscribedCount.innerHTML = '<i class="bi bi-heart"></i>&nbsp;' + changePlayCount(res.data['playlist']['subscribedCount']);
    commentCount.innerHTML = '<i class="bi bi-chat-dots"></i>&nbsp;' + changePlayCount(res.data['playlist']['commentCount']);
    description.innerText = limitDescriptionLength('介绍：' + res.data['playlist']['description']);
    more_description.innerText = '介绍：' + res.data['playlist']['description'];
    trackCount.innerText = res.data['playlist']['trackCount'] + '首歌';
}

function buildAllSongsTables(res) {
    let songs_table_tbody = document.querySelector('.songs-table-tbody');
    songs_table_tbody.innerHTML = '';
    let inner = '';
    for (let i = 0; i < res.data['songs'].length; i++) {
        inner = inner + '<tr class="songs">\n' +
            '                                        <td class="text-start">\n' +
            '                                            <div class="song-list-index">' + (i + 1) + '</div>\n' +
            '                                            <div class="song-play-button">\n' +
            '                                                <i class="bi bi-play-circle"></i>\n' +
            '                                            </div>\n' +
            '                                        </td>\n' +
            '                                        <td class="song-name">' + limitLength(res.data['songs'][i]['name']) + '</td>\n' +
            '                                        <td><span class="song-authors">' + getArString(res.data['songs'][i]['ar']) + '</td>\n' +
            '                                        <td class="song-album">' + limitLength(res.data['songs'][i]['al']['name']) + '</td>\n' +
            '                                        <td class="text-end ">\n' +
            '                                            <div class="song-time">' + changeDt(res.data['songs'][i]['dt']) + '</div>\n' +
            '                                            <div class="song-icon-button">\n' +
            '                                                <i class="bi bi-plus-lg"></i>\n' +
            '                                                <i class="bi bi-folder-plus mx-1"></i>\n' +
            '                                            </div>\n' +
            '                                        </td>\n' +
            '                                    </tr>'
    }
    songs_table_tbody.innerHTML = inner;
    inner = null;
}

function formatDate(time) {
    const date = new Date(time);
    const month = date.getMonth() + 1,//月份是从0开始的
        day = date.getDate();
    return (month < 10 ? '0' + month : month) + '月' +
        (day < 10 ? '0' + day : day) + '日';
}

function formatDate1(time) {
    const date = new Date(time);
    const year = date.getFullYear(),
        month = date.getMonth() + 1,//月份是从0开始的
        day = date.getDate();
    return year + '-' +
        (month < 10 ? '0' + month : month) + '-' +
        (day < 10 ? '0' + day : day);
}

function changePlayCount(count) {
    if (parseInt(count) >= 10000) {
        let a = count / 10000;
        return (parseInt(a + "")) + "万";
    } else {
        return count;
    }
}

function getStringsTags(tas) {
    if (tas.length === 0) {
        return ' ';
    } else {
        for (let i = 0; i < tas.length; i++) {
            let a;
            a = '#' + tas[i];
            tas[i] = a;
        }
        return tas.join(' ');
    }
}

function getArString(ar) {
    let names = [];
    for (let i = 0; i < ar.length; i++) {
        if (i > 1) {
            break;
        }
        let a;
        a = '<span class="song-author">' + ar[i]['name'] + '</span>'
        names[i] = a;
    }
    if (ar.length <= 1) {
        return names.join('/');
    } else {
        return names.join('/') + '/...';
    }
}

function changeDt(dt) {
    if (parseInt(dt) >= 1000) {
        let a = parseInt((dt / 1000) + '');
        let b = parseInt((a / 60) + '');
        let c = a - 60 * b;
        return (b < 10 ? '0' + b : b) + ':' +
            (c < 10 ? '0' + c : c);
    } else {
        return '00:00';
    }
}

function limitLength(string) {
    return string.length > 8 ? string.substring(0, 8) + '..' : string;
}

function getQueryString(name) {
    const url_string = window.location.href; // window.location.href
    const url = new URL(url_string);
    return url.searchParams.get(name);
}

function limitDescriptionLength(string) {
    let to = document.querySelector('.toggle-open');
    if (string.length > 50) {
        to.setAttribute('style', 'display:block;');
    } else {
        to.setAttribute('style', 'display:none');
    }
    return string.length > 50 ? string.substring(0, 50) + '..' : string;
}

function relatedPlaylists(res) {
    let relatedPlaylists = document.querySelector('.related-playlist-list');
    let inner = '';
    for (let i = 0; i < res.data['playlists'].length; i++) {
        inner = inner + ` <div class="d-flex flex-row mb-2 rounded border border-3 p-2"><div class="img-box">
                                    <img onclick="jumpPlayListInfo(${res.data['playlists'][i]['id']},${res.data['playlists'][i]['trackCount']})" class="related-playlist-cov rounded" src="${res.data['playlists'][i]['coverImgUrl']}" alt="">
                                    </div><div class="list-creator-name mx-2 mt-3">
                                        <div onclick="jumpPlayListInfo(${res.data['playlists'][i]['id']},${res.data['playlists'][i]['trackCount']})" class="related-playlist-name">${res.data['playlists'][i]['name']}</div>
                                        <div class="related-nickname">by&nbsp;<span>${res.data['playlists'][i]['creator']['nickname']}</span></div>
                                    </div>
                                </div>`;
    }
    relatedPlaylists.innerHTML = inner;
    inner = null;
}

function buildOtherSongs(res) {
    let type_right_nav = document.querySelector('.type-right-nav');
    type_right_nav.innerText = 'Ta的其他热门专辑'
    let relatedPlaylists = document.querySelector('.related-playlist-list');
    let inner = '';
    for (let i = 0; i < res.data['hotAlbums'].length; i++) {
        inner = inner + ` <div class="d-flex flex-row mb-2 rounded border border-3 p-2"><div class="img-box">
                                    <img onclick="jumpAlbumInfo(${res.data['hotAlbums'][i]['id']},${res.data['artist']['id']})"   class="related-playlist-cov rounded" src="${res.data['hotAlbums'][i]['blurPicUrl']}" alt="">
                                    </div><div class="list-creator-name mx-2 mt-3">
                                        <div onclick="jumpAlbumInfo(${res.data['hotAlbums'][i]['id']},${res.data['artist']['id']})"  class="related-playlist-name">${res.data['hotAlbums'][i]['name']}</div>
                                        <div class="related-nickname">${formatDate1(res.data['hotAlbums'][i]['publishTime'])}</div>
                                    </div>
                                </div>`;
    }
    relatedPlaylists.innerHTML = inner;
    inner = null;
}

function buildSimiSong(res) {
    let type_right_nav = document.querySelector('.type-right-nav');
    type_right_nav.innerText = '相似歌曲'
    let relatedPlaylists = document.querySelector('.related-playlist-list');
    let inner = '';
    for (let i = 0; i < res.data['songs'].length; i++) {
        inner = inner + ` <div class="d-flex flex-row mb-2 rounded border border-3 p-2"><div class="img-box">
                                    <img onclick="jumpSingleSongInfo(${res.data['songs'][i]['id']})"   class="related-playlist-cov rounded" src="${res.data['songs'][i]['album']['blurPicUrl']}" alt="">
                                    </div><div class="list-creator-name mx-2 mt-3">
                                        <div onclick="jumpSingleSongInfo(${res.data['songs'][i]['id']})"  class="related-playlist-name">${res.data['songs'][i]['name']}</div>
                                        <div class="related-nickname">by&nbsp;${getartists(res.data['songs'][i]['artists'])}</div>
                                    </div>
                                </div>`;
    }
    relatedPlaylists.innerHTML = inner;
    inner = null;
}

function getAlbumCreator(artists) {
    let b = [];
    for (let i = 0; i < artists.length; i++) {
        b[i] = '<span>' + artists[i]['name'] + '</span>';
    }
    return b.join('&nbsp;/&nbsp;');
}

function getlyric(str) {
    return str.replace(/\[.*?\]/g, '');
}

function getartists(ar) {
    let b = [];
    for (let i = 0; i < ar.length; i++) {
        if (i >= 2) {
            break;
        }
        b[i] = '<span>' + ar[i]['name'] + '</span>'
    }
    b = b.join('&nbsp;/&nbsp;');
    return ar.length > 2 ? b + '&nbsp;/..' : b;
}
